﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Linq;
using Abp.Localization;
using GCT.Foundation.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace GCT.Foundation.Seed.Host
{

    public class DefaultLanguagesCreator
    {
        private readonly FoundationTemplateDbContext _context;

        public DefaultLanguagesCreator(FoundationTemplateDbContext context)
        {
            _context = context;
        }

        public static List<ApplicationLanguage> InitialLanguages => GetInitialLanguages();

        private static List<ApplicationLanguage> GetInitialLanguages()
        {
            return new()
            {
                new(null, "en", "English", "famfamfam-flags us"),
                new(null, AppConsts.DefaultLanguage, "简体中文", "famfamfam-flags cn"),
            };
        }

        public void Create()
        {
            CreateLanguages();
        }

        private void CreateLanguages()
        {
            foreach (var language in InitialLanguages) AddLanguageIfNotExists(language);
        }

        private void AddLanguageIfNotExists(ApplicationLanguage language)
        {
            if (_context.Languages.IgnoreQueryFilters()
                .Any(l => l.TenantId == language.TenantId && l.Name == language.Name)) return;

            _context.Languages.Add(language);
            _context.SaveChanges();
        }
    }
}
